<template>
  <div class="app-container">
    <div class="search-bar">
      <el-form ref="queryFormRef" :model="queryParams" :inline="true">
                <el-form-item label="用户ID" prop="userId">
                      <el-input
                          v-model="queryParams.userId"
                          placeholder="用户ID"
                          clearable
                          @keyup.enter="handleQuery()"
                      />
                </el-form-item>
                <el-form-item label="所属测试项ID" prop="testId">
                      <el-input
                          v-model="queryParams.testId"
                          placeholder="所属测试项ID"
                          clearable
                          @keyup.enter="handleQuery()"
                      />
                </el-form-item>
                <el-form-item label="得分" prop="score">
                      <el-input
                          v-model="queryParams.score"
                          placeholder="得分"
                          clearable
                          @keyup.enter="handleQuery()"
                      />
                </el-form-item>
                <el-form-item label="错误单词ID列表,逗号分隔" prop="wrongWordIds">
                      <el-input
                          v-model="queryParams.wrongWordIds"
                          placeholder="错误单词ID列表,逗号分隔"
                          clearable
                          @keyup.enter="handleQuery()"
                      />
                </el-form-item>
                <el-form-item label="正确单词ID列表,逗号分隔" prop="rightWordIds">
                      <el-input
                          v-model="queryParams.rightWordIds"
                          placeholder="正确单词ID列表,逗号分隔"
                          clearable
                          @keyup.enter="handleQuery()"
                      />
                </el-form-item>
                <el-form-item label="未选择单词ID列表,逗号分隔" prop="unchooseWordIds">
                      <el-input
                          v-model="queryParams.unchooseWordIds"
                          placeholder="未选择单词ID列表,逗号分隔"
                          clearable
                          @keyup.enter="handleQuery()"
                      />
                </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">
            <template #icon><Search /></template>
            搜索
          </el-button>
          <el-button @click="handleResetQuery">
            <template #icon><Refresh /></template>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-card shadow="never">
      <div class="mb-10px">
        <el-button
            v-hasPerm="['dcyx:test-records:add']"
            type="success"
            @click="handleOpenDialog()"
        >
          <template #icon><Plus /></template>
          新增
        </el-button>
        <el-button
            v-hasPerm="['dcyx:test-records:delete']"
            type="danger"
            :disabled="removeIds.length === 0"
            @click="handleDelete()"
        >
          <template #icon><Delete /></template>
          删除
        </el-button>
      </div>

      <el-table
          ref="dataTableRef"
          v-loading="loading"
          :data="pageData"
          highlight-current-row
          border
          @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" align="center" />
                    <el-table-column
                        key="id"
                        label="测试记录ID"
                        prop="id"
                        min-width="150"
                        align="center"
                    />
                    <el-table-column
                        key="seriesId"
                        label="系列ID"
                        prop="seriesId"
                        min-width="150"
                        align="center"
                    />
                    <el-table-column
                        key="programId"
                        label="教材ID"
                        prop="programId"
                        min-width="150"
                        align="center"
                    />
                    <el-table-column
                        key="unitId"
                        label="单元ID"
                        prop="unitId"
                        min-width="150"
                        align="center"
                    />
                    <el-table-column
                        key="userId"
                        label="用户ID"
                        prop="userId"
                        min-width="150"
                        align="center"
                    />
                    <el-table-column
                        key="testId"
                        label="所属测试项ID"
                        prop="testId"
                        min-width="150"
                        align="center"
                    />
                    <el-table-column
                        key="timeConsuming"
                        label="耗时（秒）"
                        prop="timeConsuming"
                        min-width="150"
                        align="center"
                    />
                    <el-table-column
                        key="score"
                        label="得分"
                        prop="score"
                        min-width="150"
                        align="center"
                    />
                    <el-table-column
                        key="questionNumber"
                        label="题数"
                        prop="questionNumber"
                        min-width="150"
                        align="center"
                    />
                    <el-table-column
                        key="remark"
                        label="备注"
                        prop="remark"
                        min-width="150"
                        align="center"
                    />
                    <el-table-column
                        key="type"
                        label="测试类型"
                        prop="type"
                        min-width="150"
                        align="center"
                    />
                    <el-table-column
                        key="studyId"
                        label="学习ID"
                        prop="studyId"
                        min-width="150"
                        align="center"
                    />
                    <el-table-column
                        key="wrongWordIds"
                        label="错误单词ID列表,逗号分隔"
                        prop="wrongWordIds"
                        min-width="150"
                        align="center"
                    />
                    <el-table-column
                        key="rightWordIds"
                        label="正确单词ID列表,逗号分隔"
                        prop="rightWordIds"
                        min-width="150"
                        align="center"
                    />
                    <el-table-column
                        key="unchooseWordIds"
                        label="未选择单词ID列表,逗号分隔"
                        prop="unchooseWordIds"
                        min-width="150"
                        align="center"
                    />
                    <el-table-column
                        key="status"
                        label="状态"
                        prop="status"
                        min-width="150"
                        align="center"
                    />
                    <el-table-column
                        key="studentId"
                        label="学生ID"
                        prop="studentId"
                        min-width="150"
                        align="center"
                    />
                    <el-table-column
                        key="createUser"
                        label="创建者"
                        prop="createUser"
                        min-width="150"
                        align="center"
                    />
                    <el-table-column
                        key="updateUser"
                        label="更新者"
                        prop="updateUser"
                        min-width="150"
                        align="center"
                    />
        <el-table-column fixed="right" label="操作" width="220">
          <template #default="scope">
            <el-button
                v-hasPerm="['dcyx:test-records:edit']"
                type="primary"
                size="small"
                link
                @click="handleOpenDialog(scope.row.id)"
            >
              <template #icon><Edit /></template>
              编辑
            </el-button>
            <el-button
                v-hasPerm="['dcyx:test-records:delete']"
                type="danger"
                size="small"
                link
                @click="handleDelete(scope.row.id)"
            >
              <template #icon><Delete /></template>
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination
          v-if="total > 0"
          v-model:total="total"
          v-model:page="queryParams.pageNum"
          v-model:limit="queryParams.pageSize"
          @pagination="handleQuery()"
      />
    </el-card>

    <!-- 测试结果记录表单弹窗 -->
    <el-dialog
        v-model="dialog.visible"
        :title="dialog.title"
        width="500px"
        @close="handleCloseDialog"
    >
      <el-form ref="dataFormRef" :model="formData" :rules="rules" label-width="100px">
                <el-input type="hidden" v-model="formData.id" />
                <el-form-item label="系列ID" prop="seriesId">
                      <el-input
                          v-model="formData.seriesId"
                          placeholder="系列ID"
                      />
                </el-form-item>

                <el-form-item label="教材ID" prop="programId">
                      <el-input
                          v-model="formData.programId"
                          placeholder="教材ID"
                      />
                </el-form-item>

                <el-form-item label="单元ID" prop="unitId">
                      <el-input
                          v-model="formData.unitId"
                          placeholder="单元ID"
                      />
                </el-form-item>

                <el-form-item label="用户ID" prop="userId">
                      <el-input
                          v-model="formData.userId"
                          placeholder="用户ID"
                      />
                </el-form-item>

                <el-form-item label="所属测试项ID" prop="testId">
                      <el-input
                          v-model="formData.testId"
                          placeholder="所属测试项ID"
                      />
                </el-form-item>

                <el-form-item label="耗时（秒）" prop="timeConsuming">
                      <el-input
                          v-model="formData.timeConsuming"
                          placeholder="耗时（秒）"
                      />
                </el-form-item>

                <el-form-item label="得分" prop="score">
                      <el-input
                          v-model="formData.score"
                          placeholder="得分"
                      />
                </el-form-item>

                <el-form-item label="题数" prop="questionNumber">
                      <el-input
                          v-model="formData.questionNumber"
                          placeholder="题数"
                      />
                </el-form-item>

                <el-form-item label="备注" prop="remark">
                      <el-input
                          v-model="formData.remark"
                          placeholder="备注"
                      />
                </el-form-item>

                <el-form-item label="测试类型" prop="type">
                      <el-input
                          v-model="formData.type"
                          placeholder="测试类型"
                      />
                </el-form-item>

                <el-form-item label="学习ID" prop="studyId">
                      <el-input
                          v-model="formData.studyId"
                          placeholder="学习ID"
                      />
                </el-form-item>

                <el-form-item label="错误单词ID列表,逗号分隔" prop="wrongWordIds">
                      <el-input
                          v-model="formData.wrongWordIds"
                          placeholder="错误单词ID列表,逗号分隔"
                      />
                </el-form-item>

                <el-form-item label="正确单词ID列表,逗号分隔" prop="rightWordIds">
                      <el-input
                          v-model="formData.rightWordIds"
                          placeholder="正确单词ID列表,逗号分隔"
                      />
                </el-form-item>

                <el-form-item label="未选择单词ID列表,逗号分隔" prop="unchooseWordIds">
                      <el-input
                          v-model="formData.unchooseWordIds"
                          placeholder="未选择单词ID列表,逗号分隔"
                      />
                </el-form-item>

                <el-form-item label="状态" prop="status">
                      <el-input
                          v-model="formData.status"
                          placeholder="状态"
                      />
                </el-form-item>

                <el-form-item label="学生ID" prop="studentId">
                      <el-input
                          v-model="formData.studentId"
                          placeholder="学生ID"
                      />
                </el-form-item>

                <el-form-item label="创建者" prop="createUser">
                      <el-input
                          v-model="formData.createUser"
                          placeholder="创建者"
                      />
                </el-form-item>

                <el-form-item label="更新者" prop="updateUser">
                      <el-input
                          v-model="formData.updateUser"
                          placeholder="更新者"
                      />
                </el-form-item>

      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleSubmit()">确定</el-button>
          <el-button @click="handleCloseDialog()">取消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
  defineOptions({
    name: "TestRecords",
    inheritAttrs: false,
  });

  import TestRecordsAPI, { TestRecordsPageVO, TestRecordsForm, TestRecordsPageQuery } from "@/api/dcyx/test-records";

  const queryFormRef = ref();
  const dataFormRef = ref();

  const loading = ref(false);
  const removeIds = ref<number[]>([]);
  const total = ref(0);

  const queryParams = reactive<TestRecordsPageQuery>({
    pageNum: 1,
    pageSize: 10,
  });

  // 测试结果记录表格数据
  const pageData = ref<TestRecordsPageVO[]>([]);

  // 弹窗
  const dialog = reactive({
    title: "",
    visible: false,
  });

  // 测试结果记录表单数据
  const formData = reactive<TestRecordsForm>({});

  // 测试结果记录表单校验规则
  const rules = reactive({
                      userId: [{ required: true, message: "请输入用户ID", trigger: "blur" }],
                      testId: [{ required: true, message: "请输入所属测试项ID", trigger: "blur" }],
                      score: [{ required: true, message: "请输入得分", trigger: "blur" }],
                      wrongWordIds: [{ required: true, message: "请输入错误单词ID列表,逗号分隔", trigger: "blur" }],
                      rightWordIds: [{ required: true, message: "请输入正确单词ID列表,逗号分隔", trigger: "blur" }],
                      unchooseWordIds: [{ required: true, message: "请输入未选择单词ID列表,逗号分隔", trigger: "blur" }],
  });

  /** 查询测试结果记录 */
  function handleQuery() {
    loading.value = true;
          TestRecordsAPI.getPage(queryParams)
        .then((data) => {
          pageData.value = data.list;
          total.value = data.total;
        })
        .finally(() => {
          loading.value = false;
        });
  }

  /** 重置测试结果记录查询 */
  function handleResetQuery() {
    queryFormRef.value!.resetFields();
    queryParams.pageNum = 1;
    handleQuery();
  }

  /** 行复选框选中记录选中ID集合 */
  function handleSelectionChange(selection: any) {
    removeIds.value = selection.map((item: any) => item.id);
  }

  /** 打开测试结果记录弹窗 */
  function handleOpenDialog(id?: number) {
    dialog.visible = true;
    if (id) {
      dialog.title = "修改测试结果记录";
            TestRecordsAPI.getFormData(id).then((data) => {
        Object.assign(formData, data);
      });
    } else {
      dialog.title = "新增测试结果记录";
    }
  }

  /** 提交测试结果记录表单 */
  function handleSubmit() {
    dataFormRef.value.validate((valid: any) => {
      if (valid) {
        loading.value = true;
        const id = formData.id;
        if (id) {
                TestRecordsAPI.update(id, formData)
              .then(() => {
                ElMessage.success("修改成功");
                handleCloseDialog();
                handleResetQuery();
              })
              .finally(() => (loading.value = false));
        } else {
                TestRecordsAPI.add(formData)
              .then(() => {
                ElMessage.success("新增成功");
                handleCloseDialog();
                handleResetQuery();
              })
              .finally(() => (loading.value = false));
        }
      }
    });
  }

  /** 关闭测试结果记录弹窗 */
  function handleCloseDialog() {
    dialog.visible = false;
    dataFormRef.value.resetFields();
    dataFormRef.value.clearValidate();
    formData.id = undefined;
  }

  /** 删除测试结果记录 */
  function handleDelete(id?: number) {
    const ids = [id || removeIds.value].join(",");
    if (!ids) {
      ElMessage.warning("请勾选删除项");
      return;
    }

    ElMessageBox.confirm("确认删除已选中的数据项?", "警告", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    }).then(
        () => {
          loading.value = true;
                TestRecordsAPI.deleteByIds(ids)
              .then(() => {
                ElMessage.success("删除成功");
                handleResetQuery();
              })
              .finally(() => (loading.value = false));
        },
        () => {
          ElMessage.info("已取消删除");
        }
    );
  }

  onMounted(() => {
    handleQuery();
  });
</script>
